#ifndef _NET_H_
#define _NET_H_

#include <cstring>
#include <iostream>

#include "SDL/SDL_net.h"
#include "SDL/SDL_thread.h"

#define sdlerror std::cerr << "Fatalt fel, fil " __FILE__ ", rad " << __LINE__ << ": " << SDL_GetError() << std::endl;
#define sdlneterror std::cerr << "Fatalt fel, fil " __FILE__ ", rad " << __LINE__ << ": " << SDLNet_GetError() << std::endl;

/*---------------------------------

Klassen Network sköter nätverkandet.

---------------------------------*/

enum {
	SERVER, CLIENT
};

class Packet;

class Network {
public:

	IPaddress ipAddress;
	TCPsocket serverSocket, remoteSocket;
	Uint32 ipaddress;
	Uint16 port;
	bool isClient;
	SDL_Thread *thread;

	static int fetchDataWrapper( void* n );
	int fetchData( void );
	void sendData( const Packet* packet );
	bool connect( void );

	Network( bool isClient, Uint16 port, const char* ip = NULL );
	 ~Network( void );

};

extern Network* network;

class Internet {
public:
	IPaddress ipAddress;
	TCPsocket receiveSocket;
	char *myName, *remoteName;
	Internet( const char* myName, const char* remoteName );
	~Internet();
	void sendData( const char* packet );
	static int fetchDataWrapper( void* n );
	int fetchData( void );
};

extern Internet* internet;

/*---------------------------------

Klassen Packet innehåller paket som skickas av jultomten.

---------------------------------*/

enum {
	DRAG, QUIT, NYTT_SPEL, CHATTA, MUS_KLICK
}; //Packet::action

class Packet {
public:

	int len;
	int action;
	union {
		char message[504];
		struct { char x1, y1, x2, y2; }; // För drag
		struct { int mus_x, mus_y; }; // För mus_klick
		int hostsFarg; // För nytt_spel
	};

	// Roffa åt sig paktet från senaste eventet
	static Packet& getPacket( const SDL_Event& event ) {
		return *(Packet*)(event.user.data1);
	}

	// Skicka paketet
	void send( void ) {
		if( network ) {
			network->sendData( this );
		}
	}

	// Öppna paketet, dvs släng bort det...
	void clear( void ) {
		delete this;
	}

	Packet( void ) {}
	~Packet( void ) {}

};

#endif //_NET_H_
